<?php

namespace api\modules\backend\controllers;

use Yii;
use yii\rest\ActiveController;
use common\library\traits\APITrait;
use common\commands\VtCommon;
use yii\filters\auth\QueryParamAuth;
use yii\filters\Cors;

class ControllerBase extends ActiveController
{
    use APITrait;

    public function behaviors()
    {
        Yii::$app->user->identityClass = 'common\models\Admin';

        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            $this->response(VtCommon::getPackedResponse(SUCCESS, 'Success', null));
        }

        $behaviors = parent::behaviors();
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Access-Control-Allow-Origin' => ['*'],
                // restrict access to
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                // Allow only POST and PUT methods
                'Access-Control-Request-Headers' => ['*'],
                // Allow only headers 'X-Wsse'
                'Access-Control-Allow-Credentials' => null,
                // Allow OPTIONS caching
                'Access-Control-Max-Age' => 3600,
            ],
        ];
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'tokenParam' => 'token'  //例如改为‘token’
        ];
        return $behaviors;
    }

    /**
     * @param $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        if (!parent::beforeAction($action)) {
            return false;
        }

        $langId = empty(Yii::$app->request->get('lang_id')) ? 1 : Yii::$app->request->get('lang_id');

        switch ($langId) {
            case 1:
                Yii::$app->language = 'zh-CN';
                break;
            case 2:
                Yii::$app->language = 'zh-TW';
                break;
            case 3:
                Yii::$app->language = 'en';
                break;
            default:
                Yii::$app->language = 'zh-CN';
        }

        return true;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        unset($actions['create']);
        unset($actions['update']);
        unset($actions['delete']);
        unset($actions['view']);
        return $actions;
    }

    /**
     * @inheritdoc
     */
    public function afterAction($action, $result)
    {
        $result = parent::afterAction($action, $result);
        if (empty($result)) {
            $this->response(VtCommon::getPackedResponse(DATABASE_FAILED, Yii::t('app', 'DATABASE_FAILED'), null));
        } else {
            $this->success($result);
        }
    }
}
